import { existsSync, readdirSync, readFileSync } from 'fs';
import { join } from 'path';
import { logger } from '../utils/logger';
import { DeptRegistry } from '../registry/DeptRegistry';
import { Dept } from '../api/Dept';
import { IModJSON } from './Mod';

export class DeptLoader {
	constructor(readonly mod: IModJSON) {}

	private defaultDept: Partial<IDeptJSON> = {
		id: '',
		name: '',
		icon: '',
		point: 0,
		data: {},
	};

	loadDepts(path: string) {
		if (!existsSync(path)) return;
		logger.info(`Loading departments from: ${path}`);
		readdirSync(path).forEach((value) => {
			const filePath = join(path, value);
			try {
				const json = JSON.parse(readFileSync(filePath, 'utf-8'));
				const data = { ...this.defaultDept, ...json };
				this.registry(data);
			} catch (error) {
				logger.error(`Error loading department from ${filePath}: ${error}`);
			}
		});
	}

	registry(json: IDeptJSON) {
		class DeptJSON extends Dept {
			constructor(deptId: string) {
				super(deptId);
				// 部门数据
				for (const i in json.data) {
					this.setDeptData(i, json.data[i]);
				}
			}
			// 部门名称
			name: string = json.name;
			// 部门图标
			icon: string = json.icon;
			// 部门最大行动点
			pointMax: number = json.point;
		}
		DeptRegistry.registry(json.id, DeptJSON);
	}
}

export interface IDeptData {
	text: string;
	value: number;
	unit: string;
}

export interface IDeptJSON {
	id: string;
	name: string;
	icon: string;
	point: number;
	data: Record<string, IDeptData>;
}
